﻿using Cofe.Core.Actions;
using Cofe.Core.Interfaces;
using Cofe.Core.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Cofe.Core.Implements
{
    [Export(typeof(ICofeService))]
    [ServicePriority(ServicePriorityAttribute.DefaultPriority_COFE)]
    public class RenameEntry : ITransferHelper
    {
        public TransferMode GetSupportedMode(ICofeSystemInfo[] entries, ICofeDirectoryInfo fromm, ICofeDirectoryInfo too)
        {
            if (entries == null || entries.Length != 1)
                return TransferMode.None;
            
            if (EntryEqualityComparer.CompareParsePath.Equals(fromm, too))
            {
                if (!(entries[0].Properties.PrimaryPropertyProvider.IsPropertyReadOnly(CofeProperties.Name)))
                    return TransferMode.Rename;
            }
            return TransferMode.Rename;
        }

        public Task<TransferMode> TransferAsync(TransferMode mode, ICofeSystemInfo[] entries, ICofeDirectoryInfo fromm, ICofeDirectoryInfo too,
            IProgress<ProgressEventArgs> progress, System.Threading.CancellationToken cts)
        {
            throw new NotSupportedException();
        }

        public async Task<TransferMode> RenameAsync(TransferMode mode, ICofeSystemInfo entry, ICofeDirectoryInfo fromm,
            string newName, IProgress<ProgressEventArgs> progress, CancellationToken cts)
        {
            if (mode == TransferMode.Rename && GetSupportedMode(new ICofeSystemInfo[] { entry }, fromm, fromm) == TransferMode.Rename)
            {
                var pp = PropertyPair.FromValue(CofeProperties.Name, newName);
                if (!(pp.IsValid))
                    throw new ArgumentException(pp.GetValidationResult().First().ErrorMessage);
                await entry.Properties.Behaviors.SetPropertyAsync(pp);

                return TransferMode.Rename;
            }
            
            throw new NotSupportedException();
        }

        private IEntryConstructor _entryConstructor = null;
        public ITransferHelper[] _allHelpers = null;

        public IEntryConstructor EntryConstructor
        {
            get { return _entryConstructor ?? CofeServices.ServiceLocater.FindService<IEntryConstructor>(); }
            set { _entryConstructor = value; }
        }
        public ITransferHelper[] AllHelpers
        {
            get { return _allHelpers ?? CofeServices.ServiceLocater.FindAllServices<ITransferHelper>().ToArray(); }
            set { _allHelpers = value; }
        }



    }
}
